import route from '@/router/'
import axios from 'axios'
import * as constant from '@/store/yg/common/constant'
import { untransform } from "@/store/yg/common/uri"

export function trim (str) {
  if (undefined === str) {
    return '';
  }
  if (!(typeof str == 'string')) {
    return str;
  }

  return str.replace(/(^\s*)|(\s*$)/g, '');
}

export function icon (o) {
  return o.icon && o.icon.indexOf('far') >= 0 ? o.icon : 'fa fa-' + o.icon
}

export function faIconClass (path) {
  var icon = "file";
  var ext = getExt(path);
  switch (ext) {
    case 'xsl':
    case 'xslx':
      icon = "file-excel-o";
      break;
    case 'jpg':
      icon = "file-image-o";
      break;
    case 'pdf':
      icon = "file-pdf-o";
      break;
    case 'ppt':
    case 'pptx':
      icon = "file-powerpoint-o";
      break;
    case 'zip':
      icon = "file-archive-o";
      break;
  }

  return "fa fa-" + icon;
}

export function getExt (filename) {
  return filename.split('.').pop();
}

export function auth (error) {
  if ((!error.response) || error.response.status == 401) {
    window.location.href = "/#/login";
  } else if (error.response.status == 404) {
    window.location.href = "/#/";
  }
}

export function isNumber (value) {
  var ex = /^(-)?\d+(\.\d+)?$/;
  return ex.exec(value);
}

export function intersection (arr1, arr2) {
  return intersection2(arr1, arr2)
}

const intersection2 = (arr1, arr2) => {
  let arr = [];
  arr1.forEach((a, i) => {
    arr.push(a + '');
  });
  return arr2.filter(function (v) {
    return arr.indexOf(v + '') !== -1
  });
}

export function isNumberGt0 (value) {
  return isNumber(value) && value > 0;
}

export function actionPermission (displayRules, commit, data, state) {
  if (0 == Object.keys(displayRules).length) {
    return false;
  }
  let rule = displayRules[commit];
  if (!rule || rule == '-') {
    return true;
  }
  let displayRule = JSON.parse(rule);

  for (var k in displayRule) {
    if (Array.isArray(displayRule[k]) && displayRule[k].length > 0) {
      let vs = state.auth.user.roleIds;
      if (k != "ROLE_ID") {
        if (null == data[k] || undefined == data[k]) {
          vs = [];
        } else {
          vs = [data[k] + ''];
        }
      }
      if (Array.from(displayRule[k]).length == 0) {
        continue;
      }
      let intersection = intersection2(displayRule[k], vs);
      if (intersection.length == 0) {
        return false;
      }
    }
  }
  return true;
}
export function actionPermission1 (displayRules, commit, data, state) {
  if (0 == Object.keys(displayRules).length) {
    for (var i in state.main.entry.table.action) {
      let a = state.main.entry.table.action[i];
      if (a.displayRule) {
        displayRules[a.client.commit] = a.displayRule;
      }
    }
  }
  if (0 == Object.keys(displayRules).length) {
    return false;
  }
  let rule = displayRules[commit];
  if (!rule || rule == '-') {
    return true;
  }
  let displayRule = JSON.parse(rule);

  for (var k in displayRule) {
    if (Array.isArray(displayRule[k]) && displayRule[k].length > 0) {
      let vs = state.auth.user.roleIds;
      if (k != "ROLE_ID") {
        if (null == data[k] || undefined == data[k]) {
          vs = [];
        } else {
          vs = [data[k] + ''];
        }
      }
      if (Array.from(displayRule[k]).length == 0) {
        continue;
      }
      let intersection = intersection2(displayRule[k], vs);
      if (intersection.length == 0) {
        return false;
      }
    }
  }
  return true;
}
export function searchCustomerLimit(query) {
  const attrs = {
    class: 'com.tofba.app.client.statistics.StatementExportClient'
  }
  return ajax("searchCustomerSelect", {name: query}, attrs);
}
export function searchServiceCompany(query) {
  const attrs = {
    class: 'com.tofba.app.client.statistics.StatementExportClient'
  }
  return ajax("searchServiceCompanySelect", {name: query}, attrs);
}
export function searchUser(query) {
  const attrs = {
    class: 'com.tofba.app.client.statistics.StatementExportClient'
  }
  return ajax("searchUserSelect", {name: query}, attrs);
}
export function searchLoginCName(query) {
  const attrs = {
    class: 'com.tofba.app.client.statistics.StatementExportClient'
  }
  return ajax("searchLoginCNameSelect", {name: query}, attrs);
}
export function ajax (func, data, attrs) {
  if (!attrs) {
    attrs = {};
  }
  var path = attrs.uri ? attrs.uri : '#' + route.history.current.path;
  var type = attrs.type ? attrs.type : '';
  var headers = attrs.headers ? attrs.headers : {};

  if (!type) {
    if (path.startsWith('#/main/')) {
      type = 'main';
    } else if (path.startsWith('#/blank/')) {
      type = 'blank';
    }
  }
  if (type == 'mobile') {
    let suffix = '/mobile';
    if (path.indexOf(suffix, path.length - suffix.length) !== -1) {
      path = path.substring(0, path.length - suffix.length);
    }
  }

  var uri = '/api/consume/ajax?uri=' + untransform(path) + '&f=' + func + '&type=' + type;
  if (attrs.class) {
    uri += '&class=' + attrs.class;
  }
  if (attrs.q) {
    uri += '&q=' + attrs.q;
  }
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: constant.API_SERVER + uri,
      data: data,
      headers: headers,
    }).then(response => {
      resolve(response.data);
    }).catch(error => {
      if (attrs.auth) {
        auth(error);
      }
      reject(error);
    });
  });
}

export function storeSource (sources, uri) {
  if (!sources) {
    return;
  }
  for (var source in sources) {
    var key = 'source_' + source;
    var uris = [];
    if (undefined !== localStorage[key]) {
      uris = JSON.parse(localStorage[key]);
    }
    if (uris.indexOf(uri) < 0) {
      uris.push(uri);
    }
    localStorage[key] = JSON.stringify(uris);
  }
}


export function evictEntry (entry) {
  if (!entry.commit || !entry.commit.evict) {
    return;
  }
  var sources = entry.commit.evict.name.split(" ");
  for (var i in sources) {
    var key = 'source_' + sources[i];
    if (undefined !== localStorage[key]) {
      var uris = JSON.parse(localStorage[key]);
      for (var j in uris) {
        localStorage.removeItem(uris[j]);
      }
    }
  }
}

export function evictAllEntry () {
  for (var key in localStorage) {
    if (key.indexOf("main_") === 0 ||
      key.indexOf("edit_") === 0 ||
      key.indexOf("blank_") === 0 ||
      key.indexOf("board_") === 0 ||
      key.indexOf("mobile_") === 0) {
      localStorage.removeItem(key);
    }
  }
}

/**
 * @description: 获取URL参数
 * @param {*} variable 参数名
 * @return {*} 参数值
 */
export function getQueryVariable (variable) {
  const after = window.location.hash.split('?', 2)[1]
  if (after) {
    const reg = new RegExp('(^|&)' + variable + '=([^&]*)(&|$)')
    const r = after.match(reg)
    if (r != null) {
      return decodeURIComponent(r[2])
    } else {
      return false
    }
  }
}

// export function  print (printName, content, type) {

//   if(!printName) {
//     Message.error('打印机名称为空！')
//     return
//   }
//   if(!content) {
//     Message.error('打印机内容为空！')
//     return
//   }

//   return new Promise((resolve, reject) => {
//     $.post("http://127.0.0.1:8001", {
//     action: "do_print",
//     printer_name: printName,
//     print_tool: "sumatrapdf",
//     print_qty: 1,
//     label: content,
//     type: type || "pdf"
//   }).then(res=>{
//     resolve(res);
//   }).catch(err=>{
//     reject(err);
//   })
//   });
// }
